package com.ruyuan.dependency.order.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruyuan.dependency.order.entity.Order;
import com.ruyuan.dependency.order.service.OrderService;
import com.ruyuan.dependency.order.vo.CreateOrderReuqest;
import com.ruyuan.dependency.order.vo.OrderVo;
import com.ruyuan.dependency.order.vo.QueryOrderRequest;
import com.ruyuan.dependency.product.api.ProductApi;
import com.ruyuan.dependency.product.vo.SkuVo;
import com.ruyuan.seckilling.common.MapResult;
import com.ruyuan.seckilling.common.QueueKey;
import com.ruyuan.seckilling.common.message.OrderCancelMessage;
import com.ruyuan.seckilling.common.message.OrderPayMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhonghuashishan
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private ProductApi productApi;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @GetMapping
    public Order queryById(Long id) {
        return orderService.queryById(id);
    }

    @PostMapping("/queryList")
    public MapResult queryList(@RequestBody QueryOrderRequest request) {
        List<Order> orders = orderService.queryList(request);
        List<OrderVo> orderVos = new ArrayList<>();
        for (Order order : orders) {
            OrderVo orderVo = new OrderVo();
            BeanUtils.copyProperties(order, orderVo);
            orderVos.add(orderVo);
        }
        return MapResult.successResult().setDataList(orderVos);
    }

    @PostMapping
    public Boolean createOrder(@RequestBody CreateOrderReuqest request) {
        log.info("收到创建订单的请求");

        SkuVo skuVo = productApi.queryBySkuId(request.getSkuId());
        log.info("调用商品系统接口查询商品, skuVo={}", skuVo);

        Map<String, Object> attributes = new HashMap<>();
        attributes.put("activityId", request.getActivityId());
        attributes.put("sequence", request.getSequence());
        Order order = Order.builder()
                .userId(request.getUserId())
                .skuId(request.getSkuId())
                .count(request.getCount())
                .amount(request.getCount() * skuVo.getSeckillingPrice())
                .type(Order.TYPE_SECKILLING)
                .status(Order.STATUS_CREATED)
                .attributes(JSON.toJSONString(attributes))
                .build();
        orderService.save(order);
        log.info("保存订单，orderId={}，order={}", order.getId(), JSON.toJSONString(order));

        // 发送一个延时消息
        // messageDelayLevel：1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
        // 14 -> 延时10m
        // 4 -> 延时30s
        rocketMQTemplate.syncSend(QueueKey.QUEUE_CHECK_ORDER, MessageBuilder.withPayload(order.getId()).build(), 2000, 14);
        log.info("发送订单延时检查消息");
        return Boolean.TRUE;
    }

    @PostMapping("/pay")
    public MapResult payOrder(Long orderId) {
        Order order = orderService.queryById(orderId);
        if (Order.STATUS_CREATED.equals(order.getStatus())) {
            log.info("支付订单...");
            orderService.updataStatus(orderId, Order.STATUS_CREATED, Order.STATUS_PAYED);
            JSONObject attributes = JSON.parseObject(order.getAttributes());
            String message = OrderPayMessage.builder()
                    .sequence(attributes.getLong("sequence"))
                    .activityId(attributes.getLong("activityId"))
                    .userId(order.getUserId())
                    .skuId(order.getSkuId())
                    .count(order.getCount())
                    .build().toJsonString();
            rocketMQTemplate.convertAndSend(QueueKey.QUEUE_PAY_ORDER, message);
            log.info("发送订单支付的消息");
            return MapResult.successResult();
        }
        return MapResult.errorResult();
    }

    @PostMapping("/cancel")
    public MapResult cancelOrder(Long orderId) {
        Order order = orderService.queryById(orderId);
        if (Order.STATUS_CREATED.equals(order.getStatus())) {
            log.info("取消订单...");
            orderService.updataStatus(orderId, Order.STATUS_CREATED, Order.STATUS_CANCELED);
            JSONObject attributes = JSON.parseObject(order.getAttributes());
            String message = OrderCancelMessage.builder()
                    .sequence(attributes.getLong("sequence"))
                    .activityId(attributes.getLong("activityId"))
                    .userId(order.getUserId())
                    .skuId(order.getSkuId())
                    .count(order.getCount())
                    .build().toJsonString();
            rocketMQTemplate.convertAndSend(QueueKey.QUEUE_CANCEL_ORDER, message);
            log.info("发送订单取消的消息");
            return MapResult.successResult();
        }
        return MapResult.errorResult();
    }
}
